<template>
	<!-- 智助智能客服 (学生) -->
	<view class="container" :style="'height:' + windowHeight + 'px;'">
		<scroll-view scroll-y="true" :style="'height:' + windowHeight + 'px;'" class="msg-content" :scroll-into-view="scrollToView"
		 @scrolltoupper="loadHistory">
			<view :style="'height:' + (wheight - statusBarHeight) + 'px;'"></view>
			<view class="content" v-for="(item, key) in datas" :key="key" :id="'msg' + key">
				<!-- 当前聊天时间 -->
				<view class="time" v-if="item.timeText != ''">
					<text>{{ item.timeText }}</text>
				</view>
				<view>
					<!-- 客服发送的消息 -->
					<view class="msg-left" v-if="item.usr_id == accept_usr">
						<view class="avatar">
							<!-- <image :src="item.head ? item.head : defimg"></image> -->
							<headimg :realSrc="item.head"></headimg>
						</view>
						<view class="msg_content" v-if="item.messagetype == 'text'">
							<view class="item"></view>
							<view class="message">
								<text selectable="true">{{ item.text }}</text>
							</view>
						</view>
						<view class="msg_content" v-if="item.messagetype == 'image'">
							<image @tap="previewImage(item.text)" class="img" mode="aspectFit" :src="item.text"></image>
						</view>
						<view class="msg_content" v-if="item.messagetype == 'tape'">
							<view class="item"></view>
							<view class="vediomessage play" @tap="playVoice(item.text)"><i class="iconfont  iconyuyin-jieshou"></i></view>
						</view>
					</view>
					<view class="msg-right" v-if="item.usr_id === userInfo.id">
						<!-- 文本 -->
						<view class="msg_content" v-if="item.messagetype == 'text'">
							<view class="message">
								<text selectable="true">{{ item.text }}</text>
							</view>
							<view class="item"></view>
						</view>
						<!-- 图片 -->
						<view class="msg_content" v-if="item.messagetype == 'image'">
							<image @tap="previewImage(item.text)" class="img" mode="aspectFit" :src="item.text"></image>
						</view>
						<!-- 语言消息 -->
						<view class="msg_content" v-if="item.messagetype == 'tape'">
							<view class="vediomessage play" @tap="playVoice(item.text)"><i class="iconfont  iconyuyin-fasong"></i></view>
							<view class="item"></view>
						</view>
						<!-- 头像 -->
						<view class="avatar customerAvatar">
							<!-- <image :src="userInfo.avatar ? userInfo.avatar : defimg" mode=""></image> -->
							<headimg :realSrc="userInfo.avatar"></headimg>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部发送消息 -->
		<view class="information">
			<!-- 语音按钮 -->
			<view :class="['iconfont', 'iconyuyin', { iconbianji1: isShowVoice }]" @tap="showVoice"></view>
			<view class="voice-button" type="default" v-if="isShowVoice" @touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng"
			 @touchend="voiceEnd" @touchcancel="voiceCancel">
				{{ voiceTis }}
			</view>
			<input adjust-position="true" class="chat" type="text" v-model="chatMessage" v-else />
			<!-- ＋ -->
			<view class="iconfont iconxinjianbijibenjiahao" @tap="showMenu"></view>
			<view class="send" @tap="sendMsg(1)">发送</view>
		</view>
		<!-- 底部发送消息 -->
		<!-- 点击加号弹出 -->
		<view class="addShow" v-show="isShowMenu">
			<view @click="chooseImage(0)" class="addShowImg">
				<view class="iconfont iconxiangce"></view>
				照片
			</view>
			<view @click="chooseImage(1)" class="addShowPhoto">
				<view class="iconfont iconpaishe"></view>
				拍照
			</view>
		</view>

		<!-- 录音UI效果 -->
		<view class="record" :class="recording ? '' : 'hidden'">
			<view class="ing" :class="willStop ? 'hidden' : ''">
				<view class="iconfont iconyuyin-mian"></view>
			</view>
			<view class="cancel" :class="willStop ? '' : 'hidden'">
				<view class="iconfont iconquxiaoluyin"></view>
			</view>
			<view class="tis" :class="willStop ? 'change' : ''">{{ recordTis }}</view>
		</view>
		<!-- 语音提示框 -->
	</view>
</template>

<script>
	import headimg from '@/components/head_img.vue'
	import util from '@/common/util.js';
	var sourceType = [
		['album'],
		['camera'],
		['camera', 'album']
	];
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	];
	var system = uni.getSystemInfoSync();
	export default {
		data() {
			return {
				windowHeight: system.windowHeight,
				statusBarHeight: system.statusBarHeight,
				wheight: 0,
				date: '',
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeType: ['压缩', '原图', '压缩或原图'],
				sourceTypeIndex: 2,
				sizeTypeIndex: 2,
				uploadurl: '',
				isShowMenu: false,
				isShowVoice: false,
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				recording: false,
				willStop: false,
				recordTis: '手指上滑 取消发送',
				voiceTis: '按住 说话',
				recordTimer: null,
				recordLength: 0,

				userInfo: {},
				accept_usr: '',
				group_id: '',
				user_type: '',
				nicheng: '',
				chatMessage: '',
				scrollToView: '',
				datas: [],
				imgurls: []
			};
		},
		components: {
			headimg
		},
		// onPullDownRefresh() {
		// 	this.page = this.page + 1;
		// 	this.getHistory();
		// 	setTimeout(function() {
		// 		uni.stopPullDownRefresh();
		// 	}, 500);
		// },
		onLoad(e) {
			this.accept_usr = e.user_id;
			this.group_id = e.groupid;
			this.user_type = e.user_type;
			this.nicheng = e.nicheng;
			this.date = Date.parse(new Date()) / 1000;
			this.userInfo = uni.getStorageSync('userInfo');

			uni.setNavigationBarTitle({
				title: this.nicheng
			});
			//语音自然播放结束
			this.AUDIO.onEnded(res => {
				this.playMsgid = null;
			});
			// #ifndef H5
			//录音开始事件
			this.RECORDER.onStart(e => {
				this.recordBegin(e);
			});
			//录音结束事件
			this.RECORDER.onStop(e => {
				this.recordEnd(e);
			});
			// #endif
			//获取聊天记录
			this.getMsgList();
		},
		onShow() {
			//
			uni.hideKeyboard();
			this.listenMessage();
			uni.onKeyboardHeightChange(res => {
				if (res.height == 0) {
					this.wheight = this.statusBarHeight;
				} else {
					this.wheight = res.height;
				}
				// this.$nextTick(function() {
				// 	this.scrollToView = 'msg' + (this.datas.length - 1);
				// });
				// this.$forceUpdate();
			});
		},
		methods: {
			previewImage: function(url) {
				uni.previewImage({
					current: url,
					urls: [url]
				});
			},
			//获取聊天记录
			getMsgList: function() {
				var _this = this;
				var msgdata = uni.getStorageSync(_this.group_id + 'usr_type' + _this.user_type + 'user' + _this.accept_usr);
				if (msgdata) {
					_this.datas = msgdata.msgList;
					//处理聊天记录时间
					_this.datas.forEach((item, key) => {
						item.timeText = '';
						if (key == 0) {
							item.timeText = util.getAllTime(item.date);
						} else {
							if (item.date - _this.datas[key - 1].date > 300) {
								item.timeText = util.getAllTime(item.date);
							}
						}
					});
					_this.$nextTick(function() {
						_this.scrollToView = 'msg' + (_this.datas.length - 1);
					});
					_this.$forceUpdate();
					//清空未读信息数量
					util.Clearnum(_this.group_id, _this.accept_usr, _this.user_type);
				}
			},
			// 监听服务端传递的消息
			listenMessage: function() {
				var _this = this;
				uni.onSocketMessage(function(res) {
					if (res.data != 'ping') {
						console.log('收到服务器内容2：' + res.data);
						var data = JSON.parse(res.data);
						// uni.showToast({
						// 	title: JSON.stringify(data),
						// 	icon: 'none'
						// });
						if (!data.data && data.code == 225) {
							uni.showToast({
								title: '对方不在线,只能留言5条!',
								icon: 'none'
							});
						} else if (data.code == 222) {
							data = data.data;
							var arr = [];
							for (let index in data) {
								arr = arr.concat(data[index]);
								_this.datas.push(data[index]);
							}
							util.Savemsg(arr, false, false);
						} else if (data.code == 225 || data.code == 220) {
							var arr = [];
							arr.push(data.data);
							if (Number(data.data.usr_id) == Number(_this.userInfo.id)) {
								_this.datas.push(data.data);
								_this.chatMessage = '';
								_this.uploadurl = '';
								util.Savemsg(arr, false, true, _this.accept_usr, _this.user_type);
							} else if (Number(data.data.usr_id) == Number(_this.accept_usr) && Number(_this.group_id) == Number(data.data
									.class_id)) {
								_this.datas.push(data.data);
								util.Savemsg(arr, false, false);
							} else {
								util.Savemsg(arr, true, false);
							}
							//处理时间
							var length = _this.datas.length;
							if (length == 1 || _this.datas[length - 1].date - _this.datas[length - 2].date > 300) {
								_this.datas[length - 1].timeText = util.getAllTime(_this.datas[length - 1].date);
							} else {
								_this.datas[length - 1].timeText = '';
							}
						}
						_this.$nextTick(function() {
							_this.scrollToView = 'msg' + (_this.datas.length - 1);
						});
						_this.$forceUpdate();
					}
				});
			},
			// 发送消息
			sendMsg(msgType) {
				var obj = {
					head: this.userInfo.avatar,
					date: this.date,
					usr_id: this.userInfo.id,
					class_id: this.group_id,
					usr_type: 3,
					accept_usr: this.accept_usr
				};
				switch (msgType) {
					case 1:
						obj.text = this.chatMessage;
						obj.messagetype = 'text';
						break;
					case 2:
						obj.text = this.uploadurl;
						obj.messagetype = 'image';
						break;
					case 3:
						obj.text = this.uploadurl;
						obj.messagetype = 'tape';
						break;
				}

				if (this.chatMessage || this.uploadurl) {
					var _this = this;
					var iserror = false;
					uni.sendSocketMessage({
						data: JSON.stringify(obj),
						success: function(res) {
							// uni.showToast({
							// 	title: '发送成功',
							// 	icon: 'none'
							// });
						},
						fail: function(res) {
							if (res.errMsg == 'sendSocketMessage:fail WebSocket is not connected') {
								iserror = true;
							}
							// uni.showToast({
							// 	title: '发送失败' + JSON.stringify(res),
							// 	icon: 'none'
							// });
						}
					});
					if (iserror) {
						uni.closeSocket();
						clearInterval(this.sevenintervalID);
						var _this = this;
						uni.connectSocket({
							url: 'ws://' + _this.sevenUrl + '/private/message?token=' + uni.getStorageSync('token'),
							success: function(res) {
								// uni.showToast({
								// 	title: '连接成功',
								// 	icon: 'none'
								// });
								_this.sevenintervalID = setInterval(function() {
									uni.sendSocketMessage({
										data: 'ping',
										success: function(res) {},
										fail: function(res) {}
									});
								}, 10000);
							},
							fail: function(res) {
								// _this.Log(res);
								// uni.showToast({
								// 	title: '连接失败' + JSON.stringify(res),
								// 	icon: 'none'
								// });
							}
						});
					}
				}
			},
			loadHistory: function() {},
			/* 上传图片 */
			chooseImage: function(index) {
				var _this = this;
				uni.chooseImage({
					count: 1, //默认9
					sourceType: sourceType[index],
					sizeType: sizeType[this.sizeTypeIndex],
					success: function(res) {
						var url = res.tempFilePaths[0];
						_this.toupload(url, 2);
					}
				});
			},

			/**
			 * 语音方法
			 */
			// 打开底部面板
			showMenu() {
				this.isShowMenu = !this.isShowMenu;
				this.isShowVoice = false;
			},
			showVoice() {
				this.isShowVoice = !this.isShowVoice;
				this.isShowMenu = false;
			},

			//录音开始
			voiceBegin(e) {
				this.voiceTis = '松开 发送';
				if (e.touches.length > 1) {
					return;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({
					format: 'mp3'
				}); //录音开始,
			},
			//录音开始回调 设置UI效果
			recordBegin(e) {
				this.recording = true;
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000);
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.recordTis = '手指上滑 取消发送';
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送';
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送';
				}
			},
			// 结束录音
			voiceEnd(e) {
				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送';
				this.RECORDER.stop(); //录音结束
			},
			//录音结束(回调文件)
			recordEnd(e) {
				clearInterval(this.recordTimer);
				if (!this.willStop) {
					// let msg = {
					// 	length: 0,
					// 	url: e.tempFilePath
					// }
					// let min = parseInt(this.recordLength / 60);
					// let sec = this.recordLength % 60;
					// min = min < 10 ? '0' + min : min;
					// sec = sec < 10 ? '0' + sec : sec;
					// msg.length = min + ':' + sec;
					this.toupload(e.tempFilePath, 3);
				} else {
					console.log('取消发送录音');
				}
				this.willStop = false;
			},
			playVoice(msg) {
				this.AUDIO.src = msg;
				this.$nextTick(function() {
					this.AUDIO.play();
				});
			},

			/**
			 * 语音方法
			 */

			/* 上传文件 */
			toupload: function(url, index) {
				var _this = this;
				this.$uapi.apifile('api/v1/upload', {
					file: url
				}).then(res => {
					_this.uploadurl = JSON.parse(res.data).data.fileUrl;
					_this.sendMsg(index);
				});
			}
		}
	};
</script>

<style lang="scss">
	page {
		background: #f7f7f7;
		font-family: Source Han Sans CN;
		font-weight: 400;
		line-height: 54upx;
		height: 100%;
	}

	/* 语音提示框 */
	.voice-container {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 400upx;
		height: 400upx;
		background: rgba(51, 51, 51, 1);
		opacity: 0.5;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.iconyuyin1 {
		font-size: 150upx;
		color: #ffffff;
	}

	.voice-time {
		color: #ffffff;
		font-size: 40upx;
		line-height: 68upx;
	}

	/* 父容器 */
	.container {
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	/* 聊天信息滚动框 */
	.msg-content {
		width: 100%;
		flex: 1;
		overflow: auto;
		padding-bottom: 28upx;
	}

	.msg-content .content {
		padding: 0 30upx;
	}

	/* 左边客服消息 */
	.msg-left {
		display: flex;
		align-items: flex-start;
		margin-top: 48upx;

		.msg_content {
			display: flex;
			justify-content: flex-start;
			margin-left: 20upx;

			.item {
				height: 0upx;
				width: 0upx;
				border: 10upx solid;
				border-color: transparent #fff transparent transparent;
			}

			.message {
				font-size: 32upx;
				background: #ffffff;
				border-radius: 8upx;
				padding: 12upx;
				color: #333333;
				text-align: left;
				max-width: 480upx;
				word-break: break-all;
			}

			.img {
				max-width: 450upx;
			}

			.vediomessage {
				font-size: 32upx;
				background: #ffffff;
				border-radius: 8upx;
				padding: 12upx;
				display: flex;
				justify-content: flex-start;

				// 模拟录音音效动画
				@keyframes volatility {
					0% {
						background-position: 10% 0%;
					}

					20% {
						background-position: 20% 0%;
					}

					30% {
						background-position: 30% 0%;
					}

					40% {
						background-position: 40% 0%;
					}

					50% {
						background-position: 50% 0%;
					}

					70% {
						background-position: 60% 0%;
					}

					80% {
						background-position: 70% 0%;
					}

					90% {
						background-position: 80% 0%;
					}

					100% {
						background-position: 100% 0%;
					}
				}

				.iconfont {
					background-image: linear-gradient(to right, #ff9900, #fff 100%);
					background-size: 100% 100%;
					animation: volatility 1.5s ease -1.5s infinite alternate;
					-webkit-background-clip: text;
					-webkit-text-fill-color: transparent;
					color: #ff9900;
				}
			}
		}
	}

	.msg-right {
		display: flex;
		justify-content: flex-end;
		margin-top: 48upx;

		.msg_content {
			display: flex;
			justify-content: flex-end;
			margin-right: 20upx;

			.item {
				height: 0upx;
				width: 0upx;
				border: 10upx solid;
				border-color: transparent transparent transparent #fff;
			}

			.message {
				font-size: 32upx;
				background: #ffffff;
				border-radius: 8upx;
				padding: 12upx;
				color: #333333;
				text-align: left;
				max-width: 480upx;
				word-break: break-all;
			}

			.img {
				max-width: 450upx;
			}

			.vediomessage {
				font-size: 32upx;
				background: #ffffff;
				border-radius: 8upx;
				padding: 12upx;
				display: flex;
				justify-content: flex-start;
			}
		}
	}

	// .msg-right .item {
	// 	position: absolute;
	// 	left: -32upx;
	// 	top: 50%;
	// 	border: 10upx solid;
	// 	border-color: transparent transparent transparent #00D5A2;
	// 	transform: translateY(-50%) scaleY(.7) scaleX(1.2);
	// }

	.model-flex {
		align-items: flex-start;
	}

	/* 消息样式 */

	.customer-message {
		background: #00d5a2;
		color: #ffffff;
	}

	/* 头像 */
	.avatar {
		width: 80upx;
		height: 80upx;
		background: #ffffff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 客服头像 */
	.avatar image {
		width: 80upx;
		height: 80upx;
		border-radius: 50%;
	}

	/* 客户头像 */
	.customerAvatar image {
		width: 76upx;
		height: 76upx;
	}

	/* 功能模块消息框 */
	.model-message {
		width: 480upx;
		background: #ffffff;
		font-size: 32upx;
		align-items: flex-start;
		margin: 0 32upx;
	}

	.model-message .title {
		display: block;
		color: #333333;
		margin: 26upx 0 24upx 28upx;
	}

	.model-message .message-list {
		display: flex;
		align-items: center;
		margin-bottom: 44upx;
		height: 30upx;
	}

	.model-message .message-list .dian {
		display: inline-block;
		width: 14upx;
		height: 14upx;
		background-color: #333333;
		border-radius: 50%;
		margin: 0 16upx 0 28upx;
	}

	.model-message .message-list .message {
		font-size: 30upx;
		color: #00d5a2;
		margin: 0;
		padding: 0;
	}

	.feedback {
		display: flex;
		color: #333333;
		margin-left: 16upx;
		margin-bottom: 42upx;
	}

	.feedback text {
		margin-right: 20upx;
	}

	.feedback navigator {
		color: #00d5a2;
	}

	/* 右边客户端信息 */
	.msg-right {
		display: flex;
		justify-content: flex-end;
		align-items: flex-start;
		margin-top: 48upx;
	}

	.time {
		display: flex;
		justify-content: center;
		padding-top: 30upx;
	}

	.time text {
		font-size: 24upx;
		color: #999999;
	}

	.sendContent {
		float: right;
		margin-right: 30upx;
		margin: 44upx 30upx 44upx 0;
	}

	.information {
		width: 750upx;
		height: 120upx;
		background: rgba(247, 247, 247, 1);
		box-shadow: 0px -1px 6px rgba(0, 0, 0, 0.08);
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.information image {
		width: 60upx;
		height: 60upx;
	}

	.iconyuyin {
		margin-left: 30upx;
		font-size: 60upx;
		color: #666666;
	}

	.iconxinjianbijibenjiahao {
		font-size: 60upx;
		color: #666666;
	}

	/* 输入框 */
	.chat {
		width: 380upx;
		height: 68upx;
		background: #ffffff;
		border-radius: 8upx;
	}

	/* 语音按钮 */
	.voice-button {
		width: 380upx;
		height: 68upx;
		border-radius: 8upx;
		background: rgba(229, 229, 229, 1);
		text-align: center;
		line-height: 68upx;
		color: #666666;
	}

	.send {
		width: 80upx;
		height: 68upx;
		border-radius: 8upx;
		background: #ff9900;
		line-height: 68upx;
		text-align: center;
		color: #ffffff;
		font-size: 32upx;
		margin-right: 30upx;
	}

	/* 点击加显示 */
	.addShow {
		width: 750upx;
		height: 234upx;
		background: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		justify-content: flex-start;
		color: #333333;
		font-size: 26upx;
		text-align: center;
	}

	.addShowImg {
		margin-left: 64upx;
	}

	.addShowPhoto {
		margin-left: 126upx;
	}

	.iconxiangce {
		font-size: 57upx;
		color: #00d5a2;
	}

	.iconpaishe {
		font-size: 56upx;
		color: #ff9900;
	}

	.hidden {
		display: none !important;
	}

	.record {
		width: 40vw;
		height: 40vw;
		position: fixed;
		top: 55%;
		left: 30%;
		background: rgba(0, 0, 0, 0.6);
		border-radius: 20upx;

		.ing {
			width: 100%;
			height: 30vw;
			display: flex;
			justify-content: center;
			align-items: center;

			// 模拟录音音效动画
			@keyframes volatility {
				0% {
					background-position: 0% 130%;
				}

				20% {
					background-position: 0% 150%;
				}

				30% {
					background-position: 0% 155%;
				}

				40% {
					background-position: 0% 150%;
				}

				50% {
					background-position: 0% 145%;
				}

				70% {
					background-position: 0% 150%;
				}

				80% {
					background-position: 0% 155%;
				}

				90% {
					background-position: 0% 140%;
				}

				100% {
					background-position: 0% 135%;
				}
			}

			.iconfont {
				background-image: linear-gradient(to bottom, #ff9900, #fff 50%);
				background-size: 100% 200%;
				animation: volatility 1.5s ease-in-out -1.5s infinite alternate;
				-webkit-background-clip: text;
				-webkit-text-fill-color: transparent;
				font-size: 150upx;
				color: #ff9900;
			}
		}

		.cancel {
			width: 100%;
			height: 30vw;
			display: flex;
			justify-content: center;
			align-items: center;

			.iconfont {
				color: #fff;
				font-size: 150upx;
			}
		}

		.tis {
			width: 100%;
			height: 10vw;
			display: flex;
			justify-content: center;
			font-size: 28upx;
			color: #fff;

			&.change {
				color: #ff9900;
			}
		}
	}
</style>
